/**
 * Logic for account manager web page.
 */
var __AccountId = null;

function refreshAccountView(account) {
	$('#textinput-id').val(account.id);
	$('#textinput-name').val(account.name);
	$('#textinput-password').val(account.password);
	// refreshPortView(account.ports);
}

function loadAccount(accountId) {
	$.ajax({
		url : ('/loadAccount?accountId=' + accountId),
		type : 'GET',
		dataType : 'json',
		success : function(result) {
			if (result.err) {
				showMsgPopup('load account info failed:' + result.err,
						"#accountMgr");
			} else {
				refreshAccountView(result);
			}
		},
		error : function(_, status, e) {
			showMsgPopup('load account info failed:' + e, "#accountMgr");
		}
	});
}

function deleteAccount(accountId) {
	$.ajax({
		url : ('/_deleteAccount?accountId=' + accountId),
		type : 'POST',
		success : function(result) {
			if (result != 'ok') {
				showMsgPopup('load account info failed:' + result.err,
						"#accountMgr");
			} else {
				location.reload();
			}
		},
		error : function(_, status, e) {
			showMsgPopup('delete account failed:' + e, "#accountMgr");
		}
	});
}

function pageinit(){
	$('#lvAccounts').find('.accountId').each(function(i, a) {
		var input = $(a).find("input").first();
		var accountId = input.val();
		$(a).off('click').on('click', function(event) {
			__accountId = accountId;
			$("#accountName").text("Account: " + __accountId);
			loadAccount(__accountId);
			event.preventDefault();
		});
	});
	
	$('#addAccount').off('click').on('click', function(event) {
		$.mobile.changePage("/editAccount?a=newAccount", {
			transition : "flip",
			role : "dialog"
		});
		event.preventDefault();
	});
	
	$('#editAccount').off('click').on('click', function(event) {
		$.mobile.changePage("/editAccount?accountId=" + __AccountId, {
			transition : "flip",
			role : "dialog"
		});
		event.preventDefault();
	});
	
	$('#deleteAccount').off('click').on('click', function(event) {
		var id = $("#textinput-id").val();
		if (!id || id.length < 1) {
			showMsgPopup("Please select a account to delete");
			return;
		}
		var xdata = {
			title : 'Confirm delete account',
			hint : "Are you sure?",
			msg : "Delete the account with id:" + id
		};
		showConfirmDlg(xdata, function() {
			deleteAccount(id);
		});
		event.preventDefault();
	});
}

$(document).on('pageinit', function() {
	pageinit();
});
